#!/usr/bin/env bash

set -e

BIN_NAME=$0

function usage() {
    echo ""
    echo "Usage:"
    echo "$BIN_NAME [--staging | --path dbpath] [--passphrase passphrase]"
    echo ""
    echo "    Running this command without arguments will try and dump the schema of the production database in the currently booted simulator"
    echo ""
    echo "    Passphrase options:"
    echo "    --passphrase  Use the provided passphrase to decrypt the database. No quotes, just a hex string."
    echo "    (savedKey)    You can save a copy of a simulator's database key in Debug UI > Misc > Save plaintext database key. If a key is found, it'll automatically be used to decrypt the database"
    echo "    (stdin)       If a key wasn't found automatically and wasn't specified in command line args, you'll be prompted for one through standard input."
    echo ""
    echo "    Database options:"
    echo "    (default)     Target the production database of the currently booted simulator"
    echo "    --staging     Target the staging database of the currently booted simulator"
    echo "    --path        Target a sqlcipher database located at the provided path"
    echo ""
    echo "Examples:"
    echo "     $BIN_NAME"
    echo "     $BIN_NAME --staging"
    echo "     $BIN_NAME --passphrase secret --path /tmp/test.sqlite"
    echo "     $BIN_NAME --passphrase secret --staging"
}

if [[ $1 == '-h' || $1 == '--help' ]]
then
  usage
  exit 0
fi

PATH_ARG=""
KEY_ARG=""
STAGING_ARG=""

index=1
end=$#
while [[ $index -le $end ]]
do
  if [[ ${!index} == "--staging" ]]; then
    STAGING_ARG="--staging"
  elif [[ ${!index} == "--path" ]]; then
    PATH_ARG="--path"
    index=$(( index + 1 ))
    PATH_ARG+=" ${!index}"
  elif [[ ${!index} == "--passphrase" ]]; then
    KEY_ARG="--passphrase"
    index=$(( index + 1 ))
    KEY_ARG+=" ${!index}"
  fi
  index=$(( index + 1 ))
done

BASE_DIR=$(git rev-parse --show-toplevel)
cd $BASE_DIR

OUTPUT_FILE=SignalServiceKit/Resources/schema.sql

Scripts/sqlclient --quiet $STAGING_ARG $PATH_ARG $KEY_ARG -- .schema |    # Grab the schema
  grep -v -e grdb_migrations -e sqlite_sequence                      |    # Filter out oneline tables we don't care about
  sed '1s/ok//'                                                      |    # Filter out the "ok" message that sqlcipher prints for the passphrase PRAGMAs
  bundle exec anbt-sql-formatter > $OUTPUT_FILE                           # Format it and write it to the file

if [ ${PIPESTATUS[0]} -eq 0 ]; then
    echo "🌈 Successfully dumped schema to ${OUTPUT_FILE}"
else
    cat << EOS
💥 Error while trying to dump the schema.

If you see an error like "Error: SQL logic error" the passphrase is most likely wrong.
EOS

fi
